package com.dream.mqpushserver;

import com.dream.mqpushserver.handler.ServerRequestCommandHandler;
import com.dream.mqpushserver.netty.DeCoder;
import com.dream.mqpushserver.netty.EnCoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author song_
 * @Date 2020/3/25
 * @desc
 **/
// @Component
public class MqPushServerStart implements SmartLifecycle {

    private static EventLoopGroup booGroup = null;

    private static EventLoopGroup workGroup = null;

    private static Channel backDoorChannel = null;

    @PostConstruct
    public void init() {
        booGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();
    }

    @Override
    public void start() {
        System.out.println("serverStart .. ");
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(booGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, false)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        /*pipeline.addLast(new MyProtocolEnCoder());
                        pipeline.addLast(new MyProtocolDeCoder(1024*1024,1,4));*/
                        pipeline.addLast(new DeCoder());
                        pipeline.addLast(new EnCoder());
                        pipeline.addLast(new ServerRequestCommandHandler());
                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind(10001);
        backDoorChannel = channelFuture.channel();
    }

    @Override
    public void stop() {
        if (booGroup != null) {
            booGroup.shutdownGracefully();
        }
        if (workGroup != null) {
            workGroup.shutdownGracefully();
        }
    }

    @Override
    public boolean isRunning() {
        return false;
    }

    public Boolean sendMsg(Object msg) {
        if (backDoorChannel != null) {
            ChannelFuture channelFuture = backDoorChannel.writeAndFlush(msg);
            return channelFuture.isSuccess();
        }
        return false;
    }

}
